﻿using FurionApiDemo.Util.Helper;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FurionApiDemo.Core.Implement.html.Dtos
{
    public sealed class HtmlItemJson
    {
        const string FILE_NAME = "items.json";
        const string DIRECTORY = "itemsDir";
        public string CoverImage { get; set; }
        public string Date { get; set; }
        public string Title { get; set; }
        public List<ItemsOutput> Items { get; set; } = new List<ItemsOutput>();

        public static HtmlItemJson Instance { get; private set; } = null;

        public static List<string> DirectoryList { get; set; }

        private HtmlItemJson()
        { }

        /// <summary>
        /// 默认最近的文件
        /// </summary>
        static HtmlItemJson()
        {
            //先查询所有文件夹
            GetAllDate();
            if (DirectoryList.Count > 0)
            {
                //拿到最近的文件
                string FilePath = Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, DIRECTORY, DirectoryList[0], FILE_NAME);
                try
                {
                    string fileStr = FileHelper.ReadFile(FilePath);
                    if (fileStr == null)
                    {
                        Instance = new HtmlItemJson();
                        Instance.Date = DirectoryList[0];
                        Instance.Save();
                    }
                    else
                    {
                        Instance = JsonHelper.ToObject<HtmlItemJson>(fileStr);
                    }
                }
                catch (Exception ex)
                {
                    Instance = new HtmlItemJson();
                    Instance.Date = DirectoryList[0];
                    Instance.Save();
                }
            }
            else
            {
                //没有就新new一个
                Instance = new HtmlItemJson();
                Instance.Save();
            }
        }
        public static List<string> GetAllDate()
        {
            string DirectoryPath = Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, DIRECTORY);
            if (!Directory.Exists(DirectoryPath))
            {
                Directory.CreateDirectory(DirectoryPath);
            }
            string[] dirArr = Directory.GetDirectories(DirectoryPath);
            DirectoryInfo[] subFolders = new DirectoryInfo[dirArr.Length];
            for (int i = 0; i < dirArr.Length; i++)
            {
                subFolders[i] = new DirectoryInfo(dirArr[i]);
            }

            // 使用Array.Sort方法进行排序  
            Array.Sort(subFolders, (x, y) => y.CreationTime.CompareTo(x.CreationTime));
            List<string> dirList = new List<string>();
            foreach (DirectoryInfo subFolder in subFolders)
            {
                dirList.Add(subFolder.Name);
            }
            DirectoryList = dirList;
            return dirList;
        }
        public void GetDateJson(string _Date)
        {
            Date = _Date;
            //读取历史json文件
            string FilePath = Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, DIRECTORY, Date, FILE_NAME);
            try
            {
                string fileStr = FileHelper.ReadFile(FilePath);
                if (fileStr == null)
                {
                    Instance = null;
                }
                else
                {
                    Instance = JsonHelper.ToObject<HtmlItemJson>(fileStr);
                }
            }
            catch (Exception ex)
            { }
        }
        public void Save()
        {
            var dir = Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, DIRECTORY, Date);
            var fileName = Path.Combine(dir, FILE_NAME);
            FileHelper.CreateDirectory(dir);
            var jsonStr = JsonConvert.SerializeObject(Instance, Formatting.Indented);
            FileHelper.CreateFile(fileName, jsonStr);
        }
    }

    public sealed class HtmlItemJson2
    {
        public static HtmlItemJson2 Instance { get; private set; } = null;
        /// <summary>
        /// 文件目录
        /// </summary>
        const string DIRECTORY = "itemsDir";
        /// <summary>
        /// 目录文件
        /// </summary>
        const string DIRECTORY_FILE_NAME = "directory.json";
        /// <summary>
        /// 目录文件内容
        /// </summary>
        private DirectoryDto DirectoryList { get; set; } = null;
        /// <summary>
        /// 文件列表
        /// </summary>
        private List<ItemFileInfo> FileList { get; set; } = null;
        static HtmlItemJson2()
        {
            InitData();
        }
        /// <summary>
        /// 初始化数据
        /// </summary>
        private static void InitData()
        {
            // 获取文件目录信息，读取每个文件内容缓存
            Instance = new HtmlItemJson2();
            Instance.GetDirectoryInfo();
            Instance.FileList = new List<ItemFileInfo>();
            foreach (FileItem item in Instance.DirectoryList.Items)
            {
                Instance.FileList.Add(GetItemFileInfo(item.UUID));
            }
        }
        /// <summary>
        /// 获取目录
        /// </summary>
        /// <returns></returns>
        public List<FileItem> GetDirectoryList()
        {
            return Instance.DirectoryList.Items;
        }
        /// <summary>
        /// 项目内容
        /// </summary>
        /// <param name="uuid"></param>
        /// <returns></returns>
        public ItemFileInfo ItemFileInfo(string uuid)
        {
            return Instance.FileList.Find(t => t.UUID == uuid);
        }
        /// <summary>
        /// 添加一个项目文件
        /// </summary>
        /// <param name="title"></param>
        /// <param name="coverImage"></param>
        public string AddItemFile(string title, string coverImage)
        {
            try
            {
                DateTime dt = DateTime.Now;
                string uuid = GetUUID();
                Instance.DirectoryList.Items.Add(new FileItem(title, dt, uuid));
                Instance.SaveDirectoryFile();
                ItemFileInfo fileInfo = new ItemFileInfo(title, uuid, coverImage, dt);
                Instance.FileList.Add(fileInfo);
                Instance.SaveItemFile(fileInfo);
                return uuid;
            }
            catch (Exception ex)
            {
                throw new Exception("新增文件异常：" + ex.Message);
            }
        }
        /// <summary>
        /// 更新item文件
        /// </summary>
        /// <param name="uuid"></param>
        /// <param name="title"></param>
        /// <param name="coverImage"></param>
        /// <param name="isDelete"></param>
        public void UpdateItemFile(string uuid, string title, string coverImage, bool isDelete)
        {
            try
            {
                FileItem fileItem = Instance.DirectoryList.Items.Find(t => t.UUID == uuid);
                fileItem.isDelete = isDelete;
                fileItem.Title = title;
                Instance.SaveDirectoryFile();
                ItemFileInfo fileInfo = Instance.FileList.Find(t => t.UUID == uuid);
                fileInfo.Title = title;
                fileInfo.CoverImage = coverImage;
                fileInfo.isDelete = isDelete;
                Instance.SaveItemFile(fileInfo);
            }
            catch (Exception ex)
            {
                throw new Exception("更新异常：" + ex.Message);
            }
        }
        /// <summary>
        /// 获取目录文件内容
        /// </summary>
        private void GetDirectoryInfo()
        {
            string DirectoryPath = Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, DIRECTORY);
            if (Directory.Exists(DirectoryPath))
            {
                //目录存在
                string FilePath = Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, DIRECTORY, DIRECTORY_FILE_NAME);
                if (File.Exists(FilePath))
                {
                    //文件存在
                    string fileStr = FileHelper.ReadFile(FilePath);
                    Instance.DirectoryList = JsonHelper.ToObject<DirectoryDto>(fileStr);
                    return;
                }
            }
            // 没有这个目录，一定没有这个文件
            Directory.CreateDirectory(DirectoryPath);
            Instance.DirectoryList = new DirectoryDto();
            Instance.SaveDirectoryFile();
        }
        /// <summary>
        /// 获取项目文件内容
        /// </summary>
        /// <param name="uuid"></param>
        /// <returns></returns>
        private static ItemFileInfo GetItemFileInfo(string uuid)
        {
            string FilePath = Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, DIRECTORY, uuid + ".json");
            if (File.Exists(FilePath))
            {
                //文件存在
                string fileStr = FileHelper.ReadFile(FilePath);
                return JsonHelper.ToObject<ItemFileInfo>(fileStr);
            }
            return new ItemFileInfo("", GetUUID(), "", DateTime.Now);
        }
        /// <summary>
        /// 保存目录文件
        /// </summary>
        public void SaveDirectoryFile()
        {
            var dir = Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, DIRECTORY);
            var fileName = Path.Combine(dir, DIRECTORY_FILE_NAME);
            FileHelper.CreateDirectory(dir);
            var jsonStr = JsonConvert.SerializeObject(Instance.DirectoryList, Formatting.Indented);
            FileHelper.CreateFile(fileName, jsonStr);
        }
        /// <summary>
        /// 保存项目文件
        /// </summary>
        /// <param name="fileInfo"></param>
        public void SaveItemFile(ItemFileInfo fileInfo)
        {
            var dir = Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, DIRECTORY);
            var fileName = Path.Combine(dir, fileInfo.UUID+".json");
            FileHelper.CreateDirectory(dir);
            var jsonStr = JsonConvert.SerializeObject(fileInfo, Formatting.Indented);
            FileHelper.CreateFile(fileName, jsonStr);
        }
        /// <summary>
        /// 获取UUID
        /// </summary>
        /// <returns></returns>
        private static string GetUUID()
        {
            return Guid.NewGuid().ToString("N");
        }
    }

}
